package io.lvdaxian.mybatis19.builder;


import io.lvdaxian.mybatis19.session.Configuration;
import io.lvdaxian.mybatis19.type.TypeAliasRegistry;
import io.lvdaxian.mybatis19.type.TypeHandler;
import io.lvdaxian.mybatis19.type.TypeHandlerRegistry;

/**
 * 构建器的基类，建造者模式
 *
 * @author lihh
 */
public class BaseBuilder {
  protected final Configuration configuration;
  protected final TypeAliasRegistry typeAliasRegistry;
  protected final TypeHandlerRegistry typeHandlerRegistry;
  
  public BaseBuilder(Configuration configuration) {
    this.configuration = configuration;
    
    this.typeAliasRegistry = configuration.getTypeAliasRegistry();
    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  }
  
  public Configuration getConfiguration() {
    return configuration;
  }
  
  // 根据别名解析 Class 类型别名注册/事务管理器别名
  protected Class<?> resolveClass(String alias) {
    if (alias == null) {
      return null;
    }
    try {
      return resolveAlias(alias);
    } catch (Exception e) {
      throw new RuntimeException("Error resolving class. Cause: " + e, e);
    }
  }
  
  /**
   * 这里可以根据alias别名 解析出Class
   *
   * @param alias 别名
   * @return 返回 Class 字节实例
   * @author lihh
   */
  protected Class<?> resolveAlias(String alias) {
    if (null == alias) return null;
    return typeAliasRegistry.resolveAlias(alias);
  }
  
  /**
   * 解析 类型事件
   *
   * @param javaType        java 类型
   * @param typeHandlerType Java 事件 类型
   * @return 类型事件
   * @author lihh
   */
  protected TypeHandler<?> resolveTypeHandler(Class<?> javaType, Class<? extends TypeHandler<?>> typeHandlerType) {
    if (typeHandlerType == null) {
      return null;
    }
    return typeHandlerRegistry.getMappingTypeHandler(typeHandlerType);
  }
}
